import React, {Component} from 'react';
import {connect} from 'react-redux';

class cartList extends Component {
	componentDidUpdate() {
		localStorage.setItem('cartList',JSON.stringify(this.props.cartList));
	}

	reduce(id) {
		let item = this.props.cartList.find(item=>item.id===id);
		if(item.count===1){
			this.props.removeItem(id)
		}else {
			this.props.reduceCount(id);
		}
	}

	allTotal() {
		let total = 0;
		for(let i in this.props.cartList) {
			total += this.props.cartList[i].count * this.props.cartList[i].price;
		}
		return total;
	}

	allCount() {
		let count = 0;
		for(let item of this.props.cartList) {
			count += item.count;
		}
		return count;
	}

	render() {
		return (
			<div>
				<h3>购物车信息</h3>
				<table className="table table-hover">
					<thead>
						<tr>
							<th className="text-center">id</th>
							<th className="text-center">名称</th>
							<th className="text-center">价格</th>
							<th className="text-center">数量</th>
							<th className="text-center">小计</th>
							<th className="text-center">Actions</th>
						</tr>
					</thead>
					<tbody>
					{
						this.props.cartList.map(item => {
							return (
								<tr key={item.id}>
									<td className="text-center">
										{item.id}
									</td>
									<td className="text-center">
										{item.name}
									</td>
									<td className="text-center">
										{item.price}
									</td>
									<td className="text-center">
										{item.count}
									</td>
									<td className="text-center">
										{item.price*item.count}
									</td>
									<td className="text-center">
										<button className="btn btn-primary" onClick={()=>this.props.addCount(item.id)}>+</button>
										<button className="btn btn-warning" onClick={()=>this.reduce(item.id)}>-</button>
										<button className="btn btn-danger" onClick={() => this.props.removeItem(item.id)}>x</button>
									</td>
								</tr>
							)
						})
					}
					</tbody>
				</table>
				<div>
					<h3>总价：{this.allTotal()}</h3>
					<h3>总数：{this.allCount()}</h3>
					<h3>
						<button className="btn btn-danger" onClick={()=>this.props.clearCart()}>清空购物车</button>
					</h3>
				</div>
			</div>
		);
	}
}

function mapState(state) {
	return {
		cartList: state.cartList
	}
}

function mapAction(dispatch) {
	return {
		addCount: id => dispatch({
			type: 'ADD_COUNT',
			id
		}),
		reduceCount: id => dispatch({
			type: 'REDUCE_COUNT',
			id
		}),
		removeItem: id => dispatch({
			type: 'REMOVE_ITEM',
			id
		}),
		clearCart: () => dispatch({
			type: 'CLEAR_CART'
		})
	}
}

export default connect(mapState, mapAction)(cartList);